<template>
  <div class="tendency_statistics">
    <div class="selectSite">
      <getSite @handleChange="handleChange" ref="getSite_ref"></getSite>
    </div>
    <div class="tendency_statistics_detail">
      <div class="visitDetail_header">
        <div class="timeSelect">
          <!-- 所属时间模块部分 -->
          <commonDatePick :formData='formData' @select-type="selectType" @selectTimeChange="selectTimeChange" ref="commonDatePick_ref"></commonDatePick>
        </div>
        <div class="visitorTypeSelect item" v-if="isOpen">
          <!-- 所属访客类型模块部分 -->
          <section class="options">
            <span class="options_label">访客:</span>
            <div class="options_content">
              <span v-for="item in formData.selectVisitorTypeOption" :key="item.value"
                :class="formData.selectVisitorType === item.value ? 'activeOption' : ''"
                @click="selectType(item, 'selectVisitorType')">{{
                  item.label
                }}</span>
            </div>
          </section>
        </div>
        <div class="userTypeSelect item" v-if="isOpen">
          <!-- 所属设备类型模块部分 -->
          <section class="options">
            <span class="options_label">设备:</span>
            <div class="options_content">
              <span v-for="item in formData.deviceOptions" :key="item.value"
                :class="formData.deviceSelectOptions === item.value ? 'activeOption' : ''"
                @click="selectType(item, 'deviceSelectOptions')">{{
                  item.label
                }}</span>
            </div>
          </section>
        </div>
        <div class="option-content">
          <!-- <a-button @click="resetOptions">重置</a-button> -->
          <!-- <a-button :style="{ 'margin-right': '8px' }" class="addButton" type="primary"
            @click="getSourceAnalysis()">搜索</a-button> -->
          <div class="openorclose" @click="() => isOpen = true" v-if="!isOpen">
            <a>展开</a>
            <i class="iconfont icon-down" style="font-size: 24px"> </i>
          </div>
          <div class="openorclose" @click="() => isOpen = false" v-if="isOpen">
            <a>收起</a>
            <i class="iconfont icon-up" style="font-size: 24px"> </i>
          </div>
        </div>
      </div>
      <div class="tendency_statistics_charts">
        <div class="scrollSection">
          <div class="charts">
            <div class="pv_uvlists">
              <div class="tendency_statistics_item">
                <div class="selectTypes">
                  <span>显示指标：</span>
                  <a-radio-group v-model:value="showOptionsSelected"
                    :options="showOptions.map((item: any) => ({ value: item.value, label: item.label }))"
                    @change="handleChange_select" />
                </div>
              </div>
            </div>
            <div class="tendencyOnlinePie_line">
              <div id="tendencyOnlinePie"></div>
              <div id="tendencyOnline"></div>
            </div>
          </div>
          <!-- 表格展示部分 -->
          <baseTable :columns="columns.sourceStatisticsColumns" :dataSource="configData.records" :isSelect="true"
            :scroll="scroll" ref="sensitiveBaseTables" :isShowPagination="isShowPagination" :rowSelection="1"
            :total="configData.total">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.ellipsis">
                <table-tool-tip :text="text" :column="column"></table-tool-tip>
              </template>
              <template v-if="column.dataIndex == 'sourceUrl'">
                <a class="sourceUrl">{{ text }}</a>
              </template>
            </template>
          </baseTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, onBeforeMount, onUnmounted, reactive, watch, computed } from "vue";
import request from "@/api/index";
import { initEcharts } from "@/components/echarts/index";
import { optionBar, optionPie } from "./echartType/options";
import columns from "@/components/table/tableConfig/tableColumn/siteStatistics";
import baseTable from "@/components/table/baseTable.vue";
import commonDatePick from '../commonHeader/date.vue';
import getSite from '../commonHeader/getSite.vue';
import tableToolTip from "@/components/table/tableToolTip.vue";
import { transverterMss } from '@/utils/common'
// type flowColumns
interface dataSourceType {
  [propName: string]: any;
}
//data
const showOptionsSelected = ref(1);
const showOptions = ref(
  [
    { label: '浏览量(PV)', value: 1 },
    { label: '访问数(UV)', value: 2 },
    { label: 'IP数', value: 3 },
  ]
);
let seleType_label = ref('pvTypeTypeNumDto');
const sectionValue = ref();

const dataSource = ref<dataSourceType>(JSON.parse(JSON.stringify(optionBar)));
const dataSourcePie = ref<dataSourceType>(JSON.parse(JSON.stringify(optionPie)));
dataSource.value.legend.data = ['直接访问', '外部链接', '搜索引擎'];
dataSource.value.series[0].name = '直接访问';
dataSource.value.series[1].name = '外部链接';
dataSource.value.series[2].name = '搜索引擎';
const getSite_ref = ref();
const statisticsDto = ref([{
  label: '浏览量(PV)',
  param: 'pvNum',
  value: ''
}, {
  label: '访问数(UV)',
  param: 'uvNum',
  value: ''
}, {
  label: 'IP数',
  param: 'ipNum',
  value: ''
}, {
  label: '跳出率',
  param: 'bounceRate',
  value: '',
  after: '%'
}, {
  label: '平均访问时长',
  param: 'averageVisitLength',
  value: ''
},])
const dataSource_remote = ref<dataSourceType>({})
//表格展示

const commonDatePick_ref = ref();
let selectTimeRange = ref<(string | number)[]>([]); //选择时间范围
const isOpen = ref(false);

const formData = reactive<dataSourceType>({
  selectTimeOption: 1,
  TimeOptions: [{
    label: '今天',
    value: 1
  }, {
    label: '昨天',
    value: 2
  }, {
    label: '最近7天',
    value: 3
  }, {
    label: '最近30天',
    value: 4
  }],
  selectVisitorType: '',
  selectVisitorTypeOption: [
    {
      label: '全部',
      value: ''
    }, {
      label: '新访客',
      value: 0
    }, {
      label: '老访客',
      value: 1
    },
  ],
  deviceSelectOptions: '',//设备类型
  deviceOptions: [
    {
      label: '全部',
      value: ''
    }, {
      label: '计算机',
      value: 1
    }, {
      label: '移动设备',
      value: 2
    },
  ],
})
//表格数据
let configData = reactive<dataSourceType>({ total: 0, size: 10, records: [] });
let scroll: dataSourceType = reactive({ y: 200, isFixed: false }); // 表单滚动设置
const isShowPagination = false; // 是否需要配分页器
//watch
seleType_label = computed(() => showOptionsSelected.value == 1 ? 'pvTypeTypeNumDto' :
  showOptionsSelected.value == 2 ? 'uvTypeTypeNumDto' : 'ipTypeTypeNumDto')
//methods
const handleChange_select = () => {
  nextTick(() => {
    setData()
  })
}

const handleChange = (value: any) => {//选择变化
  nextTick(() => {
    sectionValue.value = getSite_ref.value.sectionValue;
    getSourceAnalysis();
  });
};
// 获取在线统计数据
const getSourceAnalysis = async () => {
  initEcharts('tendencyOnline', dataSource.value);
  initEcharts('tendencyOnlinePie', dataSourcePie.value);
  selectTimeRange.value = commonDatePick_ref.value.selectTimeRange;
  let data: dataSourceType = {
    siteId: getSite_ref.value.sectionValue,
    startTime: selectTimeRange.value[0],
    endTime: selectTimeRange.value[1],
    newVisitor: formData.selectVisitorType,
    sourceUrlType: formData.fromSectionValue,
    deviceType: formData.deviceSelectOptions
  }
  await request.getSourceAnalysis(data).then((res: dataSourceType) => {
    dataSource_remote.value = res;
    configData.records = res.excelTypeList;
    configData.records.forEach((item: dataSourceType, index: number) => {
      item.index = index + 1
      item.type = item.type === 1 ? '搜索引擎' : item.type === 2 ? '外部链接' : '直接访问'
      item.averageVisitLength = transverterMss(item.averageVisitLength)
      item.bounceRate = (item.bounceRate * 100).toFixed() + '%'
    });
  });
  nextTick(() => {
    setData();
  });
}

const setData = () => {
  let res = dataSource_remote.value;
  dataSourcePie.value.series[0].data = [{ name: '直接访问', value: res[`${seleType_label.value}`].directAccessDto.typeNum }, { name: '外部链接', value: res[`${seleType_label.value}`].externalLinksDto.typeNum }, { name: '搜索引擎', value: res[`${seleType_label.value}`].searchEngineDto.typeNum }];
  dataSource.value.series[0].data = res[`${seleType_label.value}`].directAccessNumDtoList.map((item: dataSourceType) => item.num);
  dataSource.value.series[1].data = res[`${seleType_label.value}`].externalLinksNumDtoList.map((item: dataSourceType) => item.num);
  dataSource.value.series[2].data = res[`${seleType_label.value}`].searchEngineNumDtoList.map((item: dataSourceType) => item.num);
  dataSource.value.xAxis[0].data = res[`${seleType_label.value}`].directAccessNumDtoList.map((item: dataSourceType) => item.index);
    console.log(res);
    
  
  initEcharts('tendencyOnline', dataSource.value);
  initEcharts('tendencyOnlinePie', dataSourcePie.value);
}

//选择搜索项
const selectType = (item: dataSourceType, type: string) => {
  formData[type] = item.value;
  nextTick(() => {
    getSourceAnalysis();
  })
}
const selectTimeChange = () => {
  selectTimeRange.value = commonDatePick_ref.value.selectTimeRange;
  getSourceAnalysis();
}

//onMounted

onMounted(() => {
  getSourceAnalysis();
});

</script>

<style lang="less" scoped>
.tendency_statistics {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background: #fff;
  overflow: auto;

  .scrollSection {
    overflow: auto;
    max-height: 700px;
  }

  .charts {
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 24px;

    .pv_uvlists {
      display: flex;
      padding: 24px;

      .pv_uvlists_item {
        width: 180px;
        display: flex;
        flex-direction: column;

        div:nth-of-type(2) {
          margin-top: 8px;
        }
      }

    }
  }

  .tendency_statistics_detail {
    height: calc(100% - 40px);

    .tendency_statistics_charts {
      height: calc(100% - 40px);
    }

    .visitDetail_header {
      display: flex;
      flex-wrap: wrap;
      position: relative;
      width: 90%;
      padding-top: 24px;


      .from {
        font-size: 14px;
        color: #333;
      }

      .timeSelect {
        margin-right: 24px;
        margin-bottom: 24px;
      }

      .item {
        height: 32px;
        margin-right: 24px;
        margin-bottom: 24px;
      }

      .ant-select {
        width: 100px;
      }

      .option-content {
        position: absolute;
        right: -10%;
        display: flex;
        top: 18px;
        align-items: center;
        font-size: 14px;
      }
    }
  }

  .tendencyOnlinePie_line {
    display: flex;

    #tendencyOnlinePie {
      width: 380px;
      height: 300px;
    }

    #tendencyOnline {
      flex: 1;
      height: 300px;
      margin-bottom: 24px;
    }
  }

  .sourceUrl {
    cursor: pointer;
    color: #1F6DED;
  }

}
</style>
<style lang="scss">
.tendency_statistics_detail {


  .options {
    display: flex;
    align-items: center;
    font-size: 14px;

    .options_label {
      margin-right: 12px;
    }

    .options_content {
      margin-right: 12px;
      border: 1px solid var(--theme_button_bg_color, #1F6DED);
      display: flex;
      border-radius: 4px;

      span {
        padding: 4px 14px;
        color: #333;
        border-right: 1px solid var(--theme_button_bg_color, #1F6DED);
      }

      span:nth-last-of-type(1) {
        border-right: none;
      }

      span:hover {
        background: var(--theme_button_hover_bg_color, #4892fa);
        border-color: var(--theme_button_hover_bg_color, #4892fa);
        color: #fff;
      }

      .activeOption {
        color: #fff;
        background: var(--theme_button_bg_color, #1F6DED);
      }
    }
  }
}

.tendency_statistics_charts {
  .ant-table-column-sorters {
    max-width: 100px;
  }
}

.openorclose {
  display: flex;
  align-items: center;
}
</style>